package cn.donting.web.desktop.sys.push;

import cn.donting.web.desktop.core.entity.User;
import cn.donting.web.desktop.sys.service.UserCenter;
import cn.donting.web.desktop.top.push.SysPush;
import cn.donting.web.desktop.top.push.msg.ConfirmMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

//@Component
@Slf4j
public class SysPushCenter implements SysPush {

    private HashMap<Long, PushMsg> pushMsg = new HashMap<>();

    @Autowired
    UserCenter userCenter;

    @Override
    public boolean confirm(ConfirmMsg confirmMsg, long timeout, boolean defaultActive) {
        PushMsg<ConfirmMsg, Boolean> confirmMsgPushMsg = new PushMsg<>(PushMsgEnum.CONFIRM, confirmMsg);
        confirmMsgPushMsg.setTimeout(timeout);
        confirmMsgPushMsg.setRes(defaultActive);
        User loginUser = userCenter.getLoginUser();
        if(loginUser==null){
           log.warn("loginUser is null");
           return defaultActive;
        }
        PushWebsocket pushWebsocket = PushWebsocket.getPushWebsocket(loginUser);
        if(pushWebsocket==null){
            log.warn("pushWebsocket is null");
            return defaultActive;
        }
        try {
            pushWebsocket.sendMsg(confirmMsgPushMsg);
            //等待确认
            synchronized (confirmMsgPushMsg) {
                confirmMsgPushMsg.wait(confirmMsgPushMsg.getTimeout());
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return false;
        }
        return confirmMsgPushMsg.getRes();
    }

    public void callConfirm(Long msgId, Boolean result) {
        PushMsg confirmMsgPushMsg = pushMsg.remove(msgId);
        if(confirmMsgPushMsg==null){
            log.warn("confirmMsg is null:[{}]"+msgId);
            return;
        }
        //确认msg
        synchronized (confirmMsgPushMsg) {
            confirmMsgPushMsg.setRes(result);
            //唤醒 等待确认的 线程
            confirmMsgPushMsg.notify();
        }
    }
}
